package com.chance.cc.crawler.development.scripts.pptv;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chance.cc.crawler.core.CrawlerEnum;
import com.chance.cc.crawler.core.CrawlerRecordContext;
import com.chance.cc.crawler.core.downloader.HttpPage;
import com.chance.cc.crawler.core.pipeline.result.CrawlerData;
import com.chance.cc.crawler.core.record.CrawlerRecord;
import com.chance.cc.crawler.core.record.CrawlerRequestRecord;
import com.chance.cc.crawler.core.script.crawler.CrawlerCommonScript;
import com.chance.cc.crawler.core.selector.Json;
import com.chance.cc.crawler.core.selector.Selectable;
import com.chance.cc.crawler.core.tags.LabelTag;
import com.chance.cc.crawler.core.tags.crawler.CrawlerBusinessTags;
import com.chance.cc.crawler.core.tags.crawler.CrawlerResultTags;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.chance.cc.crawler.core.CrawlerEnum.CrawlerDataType.*;
import static com.chance.cc.crawler.development.scripts.allfeild.AICCommonField.*;

/**
 * @Author Zhao.Hhuan
 * @Date Create in 2021/3/24 14:33
 * @Description pptv关键词采集脚本
 **/
public class PPTVCrawlerScript extends CrawlerCommonScript {

    private static Logger log = LoggerFactory.getLogger(PPTVCrawlerScript.class);
    private static final String DOMAIN = "pptv";
    private static final String SITE = "searchKw";
    private static final String REQUEST_AGAIN_TAG = DOMAIN + "_request_again";
    private static final String SEARCH_KW_SOURCE_URL = "searchKwSourceUrl";

    private static final String PRIFIX = "http://sou.pptv.com";
    private static final String SEARCH_URL = "http://sou.pptv.com/s_video\\S*";
    private static final String ITEM_ENTRANCE_URL = "http://v.pptv.com/show/[a-zA-Z0-9]*.html\\S*";
    private static final String ITEM_URL = "http://v.pptv.com/page/[a-zA-Z0-9]*.html\\S*";
    private static final String AUTHOR_SOURCE_URL = "http://pgc.api.pptv.com/pgc/author?id=%s";
    private static final String AUTHOR_URL = "http://pgc.api.pptv.com/pgc/author\\S*";
    private static final String COMMENT_SOURCE_URL = "http://sccdn.api.pptv.com/sc/v4/pplive/ref/vod_%s/feed/list?appplt=web&action=1&pn=0&ps=20&from=web&version=1.0.0&format=jsonp";
    private static final String COMMENT_URL = "http://sccdn.api.pptv.com/sc/v4/pplive/ref/vod_\\d+/feed/list\\S*";

    /**
     * 脚本domain定义
     *
     * @return
     */
    @Override
    public String domain() {
        return DOMAIN;
    }

    /**
     * 进入脚本的正则列表
     */
    @Override
    public void initUrlRegulars() {
        addUrlRegular(SEARCH_URL);
        addUrlRegular(ITEM_ENTRANCE_URL);
        addUrlRegular(ITEM_URL);
        addUrlRegular(COMMENT_URL);
    }

    /**
     * 是否执行脚本 ： 输入数据检查，合格的才进入脚本
     *
     * @param crawlerRequestRecord
     * @return
     */
    @Override
    public boolean crawlerCheck(CrawlerRequestRecord crawlerRequestRecord) {
        String siteTag = crawlerRequestRecord.tagsCreator().bizTags().getCategoryTag().getKVTagStrVal("site");
        return siteTag.equals(SITE);
    }

    @Override
    public List<CrawlerRecord> prepareRequest(CrawlerRequestRecord requestRecord, List<CrawlerRequestRecord> supportSourceRecords) {
        List<CrawlerRecord> crawlerRecords = new ArrayList<>();
        for (CrawlerRequestRecord supportSourceRecord : supportSourceRecords) {
            String url = supportSourceRecord.getHttpRequest().getUrl();
            if (url.contains("keys")) {
                initKeyword(requestRecord, supportSourceRecord, crawlerRecords);
            }
        }

        requestRecord.getHttpRequest().addHeader("User-Agent",getRandomUA());
        return crawlerRecords;
    }

    /**
     * 解析链接方法
     *
     * @param crawlerRequestRecord
     * @param httpPage
     * @return
     */
    @Override
    public List<CrawlerRequestRecord> parseLinks(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        List<CrawlerRequestRecord> parsedLinks = new ArrayList<CrawlerRequestRecord>();
        String requestUrl = crawlerRequestRecord.getHttpRequest().getUrl();

        if (!httpPage.isDownloadSuccess() || (httpPage.getStatusCode() != 200 && httpPage.getStatusCode() != 404)) {
            log.error("{} status code : [{}]！will retry",requestUrl,httpPage.getStatusCode());
            requestAgainCrawlerRecord(parsedLinks, crawlerRequestRecord);
            crawlerRequestRecord.setNeedWashPage(false);
            return parsedLinks;
        }

        if(httpPage.getStatusCode() == 404){
            log.error("{} status code : [{}]",requestUrl,httpPage.getStatusCode());
            crawlerRequestRecord.setNeedWashPage(false);
            return parsedLinks;
        }

        if (requestUrl.matches(SEARCH_URL)) {
            searchUrlRecord(crawlerRequestRecord, httpPage, parsedLinks);
        }

        if (requestUrl.matches(ITEM_ENTRANCE_URL)) {
            itemEntranceUrlRecord(crawlerRequestRecord, httpPage, parsedLinks);
        }

        if (requestUrl.matches(ITEM_URL)) {
            itemUrlRecord(crawlerRequestRecord, httpPage, parsedLinks);
        }

        if (requestUrl.matches(COMMENT_URL)) {
            commentUrlRecord(crawlerRequestRecord, httpPage, parsedLinks);
        }

        return parsedLinks;
    }

    private void searchUrlRecord(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage, List<CrawlerRequestRecord> parsedLinks) {
        String requestUrl = httpPage.getRequest().getUrl();
        String keyword = (String) httpPage.getRequest().getExtras().get("keyword");
        if(!requestUrl.contains("pn")){
            List<String> all = httpPage.getHtml().xpath("//div[@class=\"no-result\"]//text()").all();
            if(all != null && all.size() > 0){
                StringBuffer sbf = new StringBuffer();
                for (String s : all) {
                    sbf.append(s);
                }
                log.error(sbf.toString().trim());
                return;
            }
        }
        //下一页
        String nextUrl = httpPage.getHtml().xpath("//a[text()='下一页']/@href").get();
        if (StringUtils.isNotBlank(nextUrl) && !nextUrl.contains("java")) {
            nextUrl = PRIFIX + StringEscapeUtils.unescapeHtml(nextUrl);
            CrawlerRequestRecord turnRecord = CrawlerRequestRecord.builder()
                    .turnPageRequest(crawlerRequestRecord)
                    .httpUrl(nextUrl)
                    .releaseTime(System.currentTimeMillis())
                    .copyBizTags()
                    .copyResultTags()
                    .build();
            turnRecord.getHttpRequest().setExtras(crawlerRequestRecord.getHttpRequest().getExtras());
            parsedLinks.add(turnRecord);
        }

        //文章列表解析
        List<Selectable> nodes = httpPage.getHtml().xpath("//div[@class=\"news-list\"]/ul/li").nodes();
        for (Selectable node : nodes) {
            String itemUrl = node.xpath(".//h5/a/@href").get();
            if (StringUtils.isBlank(itemUrl)) {
                continue;
            } else {
                itemUrl = "http:" + itemUrl;
            }

            String releaseTime = node.xpath(".//span[@class=\"shortview-time\"]/text()").get();
            if (StringUtils.isBlank(releaseTime)) {
                releaseTime = node.xpath(".//div[@class=\"info-block\"]/p[1]/text()").get();
            }

            if (StringUtils.isBlank(releaseTime)) {
                continue;
            }
            try {
                long releaseTimeToLong = DateUtils.parseDate(releaseTime.trim(), "yyyy-MM-dd").getTime();
                CrawlerRequestRecord itemRecord = CrawlerRequestRecord.builder()
                        .itemPageRequest(crawlerRequestRecord)
                        .httpUrl(itemUrl)
                        .recordKey(itemUrl + keyword)
                        .releaseTime(releaseTimeToLong)
                        .copyBizTags()
                        .needWashed(false)
                        .copyResultTags()
                        .build();
                String channelId = washContent("'channelId':'\\d+'",node.xpath(".//h5/a/@ext_info").get());
                if (StringUtils.isNotBlank(channelId)) {
                    String s = channelId.split(":")[1];
                    String substring = s.substring(s.indexOf("'") + 1, s.lastIndexOf("'"));
                    itemRecord.getHttpRequest().addExtra("channelId", substring);
                }
                parsedLinks.add(itemRecord);
            } catch (ParseException e) {
                log.error(e.getMessage());
            }
        }

        List<Selectable> nodes1 = httpPage.getHtml().xpath("//div[@class=\"positive-box clearfix\"]").nodes();
        for (Selectable selectable : nodes1) {
            String itemUrl = selectable.xpath("./a/@href").get();
            if (StringUtils.isBlank(itemUrl)) {
                continue;
            }else{
                itemUrl = "http:" + itemUrl;
            }

            CrawlerRequestRecord record = CrawlerRequestRecord.builder()
                    .itemPageRequest(crawlerRequestRecord)
                    .httpUrl(itemUrl)
                    .releaseTime(System.currentTimeMillis())
                    .needWashed(false)
                    .copyBizTags()
                    .copyResultTags()
                    .build();
            String channelId = washContent("'channelId':'\\d+'", selectable.xpath("./a/@ext_info").get());
            if (StringUtils.isNotBlank(channelId)) {
                String s = channelId.split(":")[1];
                String substring = s.substring(s.indexOf("'") + 1, s.lastIndexOf("'"));
                record.getHttpRequest().addExtra("channelId", substring);
            }
            parsedLinks.add(record);
        }
    }

    private void itemEntranceUrlRecord(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage, List<CrawlerRequestRecord> parsedLinks) {
        String requestUrl = httpPage.getRequest().getUrl();
        String url = requestUrl.replace("show", "page");

        CrawlerRequestRecord itemRecord = CrawlerRequestRecord.builder()
                .itemPageRequest(crawlerRequestRecord)
                .httpUrl(url)
                .releaseTime(crawlerRequestRecord.getReleaseTime())
                .copyBizTags()
                .needWashed(false)
                .copyResultTags()
                .build();
        itemRecord.getHttpRequest().setExtras(crawlerRequestRecord.getHttpRequest().getExtras());
        parsedLinks.add(itemRecord);
    }

    private void itemUrlRecord(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage, List<CrawlerRequestRecord> parsedLinks) {
        //判断是否是一个合集
        List<Selectable> nodes = httpPage.getHtml().xpath("//ul[@class=\"cf\"]/li").nodes();
        if (nodes.size() < 1) {
            //不是一个合集
            crawlerRequestRecord.setNeedWashPage(true);
            String requestUrl = httpPage.getRequest().getUrl();

            //author
            Map<String, Object> extras = httpPage.getRequest().getExtras();
            if (extras != null) {
                String channelId = (String) extras.get("channelId");

                if (StringUtils.isNotBlank(channelId)) {
                    String url = String.format(AUTHOR_SOURCE_URL, channelId);
                    CrawlerRequestRecord authorRecord = CrawlerRequestRecord.builder()
                            .itemPageRequest(crawlerRequestRecord)
                            .httpUrl(url)
                            .releaseTime(System.currentTimeMillis())
                            .notFilterRecord()
                            .needWashed(false)
                            .needParsed(false)
                            .requestLabelTag(CrawlerEnum.CrawlerRequestType.internalDownload)
                            .build();
                    parsedLinks.add(authorRecord);
                }
            } else {
                crawlerRequestRecord.getHttpRequest().addExtra("author", "");
            }

            String id = washContent("\"id\":\\d+", httpPage.getRawText());
            if (StringUtils.isNotBlank(id)) {
                //comments
                String[] split = id.split(":");
                String likesUrl = String.format(COMMENT_SOURCE_URL, split[1]);
                CrawlerRequestRecord likeRecord = CrawlerRequestRecord.builder()
                        .itemPageRequest(crawlerRequestRecord)
                        .httpUrl(likesUrl)
                        .recordKey(likesUrl + "internal")
                        .releaseTime(crawlerRequestRecord.getReleaseTime())
                        .notFilterRecord()
                        .needWashed(false)
                        .needParsed(false)
                        .requestLabelTag(CrawlerEnum.CrawlerRequestType.internalDownload)
                        .build();
                parsedLinks.add(likeRecord);

                CrawlerResultTags resultTags = crawlerRequestRecord.tagsCreator().resultTags();
                if (resultTags.hasDataType(comment)) {
                    resultTags.getCategoryTag().removeLabelTag("comment");

                    CrawlerRequestRecord filterRecord = resultTags.getCategoryTag().getKVTagObjVal("comment_filter_record", CrawlerRequestRecord.class);
                    if (filterRecord == null) {
                        log.error("filter record can not null !");
                        return;
                    }

                    String commentUrl = String.format(COMMENT_SOURCE_URL, split[1]);
                    CrawlerRequestRecord commentRecord = CrawlerRequestRecord.builder()
                            .turnPageRequest(crawlerRequestRecord)
                            .httpUrl(commentUrl)
                            .releaseTime(System.currentTimeMillis())
                            .notFilterRecord()
                            .copyBizTags()
                            .needWashed(true)
                            .resultLabelTag(comment)
                            .build();
                    commentRecord.getHttpRequest().addExtra("articleUrl", requestUrl);
                    commentRecord.setFilter(filterRecord.getFilter());
                    commentRecord.setFilterInfos(filterRecord.getFilterInfos());
                    parsedLinks.add(commentRecord);
                }
            } else {
                log.error("id is null!");
                crawlerRequestRecord.getHttpRequest().addExtra("comments", "0");
            }
        } else {
            for (Selectable node : nodes) {
                String itemUrl = node.xpath("./a/@href").get();
                if (StringUtils.isBlank(itemUrl)) {
                    continue;
                }

                String releaseTime = node.xpath(".//span[@class=\"date\"]").get();
                if (StringUtils.isBlank(releaseTime)) {
                    continue;
                }

                try {
                    long releaseTimeToLong = DateUtils.parseDate(releaseTime, "yyyy-MM-dd").getTime();
                    CrawlerRequestRecord record = CrawlerRequestRecord.builder()
                            .itemPageRequest(crawlerRequestRecord)
                            .httpUrl(itemUrl)
                            .releaseTime(releaseTimeToLong)
                            .needWashed(false)
                            .copyBizTags()
                            .copyResultTags()
                            .build();

                    record.getHttpRequest().addExtra("channelId", node.xpath("./a/@cid").get());
                    parsedLinks.add(record);
                } catch (ParseException e) {
                    log.error(e.getMessage());
                }
            }
        }
    }

    private void commentUrlRecord(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage, List<CrawlerRequestRecord> parsedLinks) {
        String msg = httpPage.getJson().jsonPath($_type + ".msg").get();
        if(StringUtils.isBlank(msg) && "服务正在闭关修炼".equals(msg)){
            log.error("requestUrl is [{}],msg is [{}]",httpPage.getRequest().getUrl(),msg);
            crawlerRequestRecord.setNeedWashPage(false);
        }else{
            try {
                httpPage.getJson().jsonPath($_type + ".data.page_list").all();
            } catch (Exception e) {
                log.error("{} comment download is error!will retry",crawlerRequestRecord.getHttpRequest().getUrl());
                requestAgainCrawlerRecord(parsedLinks, crawlerRequestRecord);
                crawlerRequestRecord.setNeedWashPage(false);
                return;
            }
            List<String> all = httpPage.getJson().jsonPath($_type + ".data.page_list").all();
            if (all.size() < 1) {
                return;
            }

            //评论翻页
            String requestUrl = httpPage.getRequest().getUrl();
            String[] split = requestUrl.split("\\?");
            String nextUrl = split[0] + "?";
            List<NameValuePair> parse = URLEncodedUtils.parse(split[1], Charset.defaultCharset());
            for (NameValuePair nameValuePair : parse) {
                String name = nameValuePair.getName();
                String value = nameValuePair.getValue();
                if ("pn".equals(name)) {
                    nextUrl = nextUrl + name + "=" + (Integer.parseInt(value) + 1) + "&";
                } else {
                    nextUrl = nextUrl + name + "=" + value + "&";
                }
            }
            nextUrl = nextUrl.substring(0, nextUrl.length() - 1);
            CrawlerRequestRecord commentRecord = CrawlerRequestRecord.builder()
                    .turnPageRequest(crawlerRequestRecord)
                    .httpUrl(nextUrl)
                    .releaseTime(System.currentTimeMillis())
                    .copyBizTags()
                    .needWashed(true)
                    .copyResultTags()
                    .build();
            commentRecord.getHttpRequest().setExtras(crawlerRequestRecord.getHttpRequest().getExtras());
            parsedLinks.add(commentRecord);
        }
    }

    @Override
    public void afterInternalDownload(CrawlerRequestRecord crawlerRecord, List<CrawlerRequestRecord> internalDownloadRecords, List<CrawlerRequestRecord> links) {
        for (CrawlerRequestRecord internalDownloadRecord : internalDownloadRecords) {
            HttpPage page = internalDownloadRecord.getInternalDownloadPage();
            String url = page.getRequest().getUrl();

            String comments = "0";
            if (url.matches(COMMENT_URL)) {
                try {
                    comments = page.getJson().jsonPath($_type + ".data.total").get();
                } catch (Exception e) {
                    String msg = page.getJson().jsonPath($_type + ".msg").get();
                    if(StringUtils.isNotBlank(msg) && "服务正在闭关修炼".equals(msg)){
                        comments = "0";
                    }else{
                        requestAgainCrawlerRecord(links,crawlerRecord);
                        crawlerRecord.setNeedWashPage(false);
                        return;
                    }
                }
                crawlerRecord.getHttpRequest().addExtra("comments",comments);
            }

            String author = "";
            if(url.matches(AUTHOR_URL)){
                try {
                    author = page.getJson().jsonPath($_type + ".data.nickName").get();
                } catch (Exception e) {
                    requestAgainCrawlerRecord(links,crawlerRecord);
                    crawlerRecord.setNeedWashPage(false);
                    return;
                }
                crawlerRecord.getHttpRequest().addExtra("author",author);
            }
        }

    }

    @Override
    public List<CrawlerData> washPage(CrawlerRequestRecord crawlerRecord, HttpPage page) {
        List<CrawlerData> crawlerDataList = new ArrayList<>();
        CrawlerResultTags crawlerResultTags = crawlerRecord.tagsCreator().resultTags();
        String url = page.getRequest().getUrl();

        if (crawlerResultTags.hasDataType(article)) {
            crawlerDataList.add(washArticle(crawlerRecord, page));
        }

        if (crawlerResultTags.hasDataType(interaction)) {
            crawlerDataList.add(washInteraction(crawlerRecord, page));
        }

        if (crawlerResultTags.hasDataType(comment)) {
            crawlerDataList.addAll(washComment(crawlerRecord, page));
        }

        return crawlerDataList;
    }

    private CrawlerData washArticle(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        String itemUrl = httpPage.getRequest().getUrl();
        String articleKey = itemUrl.substring(itemUrl.lastIndexOf("/") + 1, itemUrl.lastIndexOf("."));

        Map<String, Object> extras = httpPage.getRequest().getExtras();
        String author = (String) extras.get("author");
        String title = httpPage.getHtml().xpath("//h1/text()").get();
        List<String> all = httpPage.getHtml().xpath("//div[@class=\"intro j_intro\"]//dd//text()").all();
        StringBuffer contentBf = new StringBuffer();
        for (String data : all) {
            contentBf.append(data).append(" ");
        }
        CrawlerData crawlerData = CrawlerData.builder()
                .data(crawlerRequestRecord, httpPage)
                .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), CrawlerEnum.CrawlerDataType.article.enumVal(), articleKey))
                .resultLabelTag(CrawlerEnum.CrawlerDataType.valueOf("article"))
                .url(itemUrl)
                .releaseTime(crawlerRequestRecord.getReleaseTime())
                .addContentKV(Field_Content, contentBf.toString())
                .addContentKV(Field_Title, title)
                .addContentKV(Field_Author, author)
                .build();
        return crawlerData;
    }

    private CrawlerData washInteraction(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        String itemUrl = httpPage.getRequest().getUrl();
        String articleKey = itemUrl.substring(itemUrl.lastIndexOf("/") + 1, itemUrl.lastIndexOf("."));

        String comments = (String) httpPage.getRequest().getExtras().get("comments");

        CrawlerData crawlerData = CrawlerData.builder()
                .data(crawlerRequestRecord, httpPage)
                .parentId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), CrawlerEnum.CrawlerDataType.article.enumVal(), articleKey))
                .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), interaction.enumVal(), articleKey))
                .resultLabelTag(CrawlerEnum.CrawlerDataType.valueOf("interaction"))
                .url(itemUrl)
                .releaseTime(crawlerRequestRecord.getReleaseTime())
                .addContentKV(Field_I_Comments, comments)
                .build();

        return crawlerData;
    }

    private List<CrawlerData> washComment(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        List<CrawlerData> crawlerDataList = new ArrayList<>();
        String requestUrl = httpPage.getRequest().getUrl();
        String articleUrl = (String) httpPage.getRequest().getExtras().get("articleUrl");
        String articleKey = articleUrl.substring(articleUrl.lastIndexOf("/") + 1, articleUrl.lastIndexOf("."));

        List<String> commentList = httpPage.getJson().jsonPath($_type + ".data.page_list").all();
        for (String data : commentList) {
            JSONObject jsonObject = JSONObject.parseObject(data);
            String commentId = jsonObject.getString("id");
            JSONObject userInfo = jsonObject.getJSONObject("user");
            String author = userInfo.getString("nick_name");
            long timestamp = jsonObject.getLong("create_time");
            String content = jsonObject.getString("content");
            String likes = jsonObject.getString("up_ct");
            String comments = jsonObject.getString("reply_ct");

            JSONArray replies = jsonObject.getJSONArray("replies");
            if (replies != null) {
                for (Object reply : replies) {
                    JSONObject replyJson = (JSONObject) reply;
                    String replyCommentId = replyJson.getString("id");
                    JSONObject replyUserInfo = replyJson.getJSONObject("user");
                    String replyAuthor = replyUserInfo.getString("nick_name");
                    long replyTimestamp = jsonObject.getLong("create_time");
                    String replyContent = replyJson.getString("content");
                    String replyLikes = replyJson.getString("up_ct");
                    String replyComments = replyJson.getString("reply_ct");

                    CrawlerData crawlerData = CrawlerData.builder()
                            .data(crawlerRequestRecord, httpPage)
                            .parentId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), CrawlerEnum.CrawlerDataType.article.enumVal(), articleKey))
                            .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), comment.enumVal(), replyCommentId))
                            .resultLabelTag(CrawlerEnum.CrawlerDataType.valueOf("comment"))
                            .releaseTime(replyTimestamp)
                            .url(requestUrl)
                            .requestLabelTag(CrawlerEnum.CrawlerRequestType.filter)
                            .requestLabelTag(CrawlerEnum.CrawlerRequestType.result)
                            .addContentKV(Field_Author, replyAuthor)
                            .addContentKV(Field_Content, replyContent)
                            .addContentKV(Field_I_Likes, replyLikes)
                            .addContentKV(Field_I_Comments, replyComments)
                            .build();
                    crawlerDataList.add(crawlerData);
                }
            }

            CrawlerData crawlerData = CrawlerData.builder()
                    .data(crawlerRequestRecord, httpPage)
                    .parentId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), CrawlerEnum.CrawlerDataType.article.enumVal(), articleKey))
                    .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), comment.enumVal(), commentId))
                    .resultLabelTag(CrawlerEnum.CrawlerDataType.valueOf("comment"))
                    .releaseTime(timestamp)
                    .url(requestUrl)
                    .requestLabelTag(CrawlerEnum.CrawlerRequestType.filter)
                    .requestLabelTag(CrawlerEnum.CrawlerRequestType.result)
                    .addContentKV(Field_Author, author)
                    .addContentKV(Field_Content, content)
                    .addContentKV(Field_I_Likes, likes)
                    .addContentKV(Field_I_Comments, comments)
                    .build();
            crawlerDataList.add(crawlerData);
        }
        return crawlerDataList;
    }

    private static String washContent(String regx, String input) {
        Pattern compile = Pattern.compile(regx);
        Matcher matcher = compile.matcher(input);
        List<String> urlList = new ArrayList<>();
        while (matcher.find()) {
            return matcher.group(0);
        }
        return null;
    }

    @Override
    public void afterExecute(CrawlerRecordContext crawlerRecordContext) {

    }

    private void requestAgainCrawlerRecord(List<CrawlerRequestRecord> crawlerRequestRecords, CrawlerRequestRecord crawlerRecord) {
        CrawlerBusinessTags crawlerBusinessTags = crawlerRecord.tagsCreator().bizTags();
        int count = 0;
        if (crawlerBusinessTags.hasKVTag(REQUEST_AGAIN_TAG)) {
            count = (int) crawlerBusinessTags.getCategoryTag().getKVTag(REQUEST_AGAIN_TAG).getVal();
            if (count >= 5) {
                log.error(DOMAIN + " download page the number of retries exceeds the limit" +
                        ",request url {}", crawlerRecord.getHttpRequest().getUrl());
                return;
            }
        }

        String requestUrl = crawlerRecord.getHttpRequest().getUrl();
        LabelTag type = crawlerRecord.tagsCreator().requestTags().getCategoryTag().getLabelTags().get("turn_page_item_request");
        CrawlerRequestRecord crawlerRequestRecord = null;
        if (type == null) {
            crawlerRequestRecord = CrawlerRequestRecord.builder()
                    .turnPageRequest(crawlerRecord)
                    .httpUrl(requestUrl)
                    .releaseTime(crawlerRecord.getReleaseTime())
                    .recordKey(crawlerRecord.getRecordKey() + count)
                    .notFilterRecord()
                    .copyBizTags()
                    .copyResultTags()
                    .build();
        } else {
            crawlerRequestRecord = CrawlerRequestRecord.builder()
                    .itemPageRequest(crawlerRecord)
                    .httpUrl(requestUrl)
                    .releaseTime(crawlerRecord.getReleaseTime())
                    .recordKey(crawlerRecord.getRecordKey() + count)
                    .copyBizTags()
                    .copyResultTags()
                    .build();
        }

        if (crawlerRequestRecord == null) {
            return;
        }

        crawlerRequestRecord.getHttpRequest().setExtras(crawlerRecord.getHttpRequest().getExtras());
        crawlerRequestRecord.getHttpRequest().setHeaders(crawlerRecord.getHttpRequest().getHeaders());
        crawlerRequestRecord.setNeedWashPage(crawlerRecord.isNeedWashPage());
        crawlerRequestRecord.setNeedParsedPage(crawlerRecord.isNeedParsedPage());
        crawlerRequestRecord.tagsCreator().bizTags().addCustomKV(REQUEST_AGAIN_TAG, ++count);
        crawlerRequestRecords.add(crawlerRequestRecord);
    }

    private void initKeyword(CrawlerRequestRecord requestRecord, CrawlerRequestRecord supportSourceRecord, List<CrawlerRecord> crawlerRecords) {
        HttpPage internalDownloadPage = supportSourceRecord.getInternalDownloadPage();
        Map<String, Object> extras = requestRecord.getHttpRequest().getExtras();
        String searchSourceUrl = (String) extras.get(SEARCH_KW_SOURCE_URL);
        if (StringUtils.isBlank(searchSourceUrl)) {
            log.error("search kw source url can not null!");
            return;
        }
        Json json = internalDownloadPage.getJson();
        String msg = json.jsonPath($_type + ".msg").get();
        if (!"success".equals(msg)) {
            log.error("keyword page [{}] download error!", internalDownloadPage.getRequest().getUrl());
            return;
        }

        List<String> all = json.jsonPath($_type + ".content").all();
        for (String data : all) {
            JSONObject jsonObject = JSONObject.parseObject(data);
            String keyword = jsonObject.getString("keyword");

            try {
                String url = String.format(searchSourceUrl, URLEncoder.encode(keyword, "UTF-8"));
                CrawlerRequestRecord turnRecord = CrawlerRequestRecord.builder()
                        .turnPageRequest(requestRecord)
                        .httpUrl(url)
                        .releaseTime(System.currentTimeMillis())
                        .notFilterRecord()
                        .copyBizTags()
                        .copyResultTags()
                        .build();
                turnRecord.tagsCreator().bizTags().addKeywords(keyword);
                turnRecord.getHttpRequest().addExtra("keyword",keyword);
                crawlerRecords.add(turnRecord);
            } catch (UnsupportedEncodingException e) {
                log.error(e.getMessage());
            }
        }
    }

    private static List<String> agentList = new ArrayList<>();

    static {
        agentList.add("Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");
        agentList.add("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36");
        agentList.add("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36");
        agentList.add("Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2226.0 Safari/537.36");
        agentList.add("Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko");
        agentList.add("Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko");
        agentList.add("Mozilla/5.0 (compatible; MSIE 10.6; Windows NT 6.1; Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0");
        agentList.add("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 7.0; InfoPath.3; .NET CLR 3.1.40767; Trident/6.0; en-IN)");
        agentList.add("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)");
        agentList.add("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)");
        agentList.add("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/5.0)");
        agentList.add("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/4.0; InfoPath.2; SV1; .NET CLR 2.0.50727; WOW64)");
        agentList.add("Mozilla/5.0 (compatible; MSIE 10.0; Macintosh; Intel Mac OS X 10_7_3; Trident/6.0)");
        agentList.add("Mozilla/4.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/5.0)");
        agentList.add("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/532.2 (KHTML, like Gecko) ChromePlus/4.0.222.3 Chrome/4.0.222.3 Safari/532.2");
        agentList.add("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.28.3 (KHTML, like Gecko) Version/3.2.3 ChromePlus/4.0.222.3 Chrome/4.0.222.3 Safari/525.28.3");
        agentList.add("Opera/9.80 (X11; Linux i686; Ubuntu/14.10) Presto/2.12.388 Version/12.16");
        agentList.add("Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14");
        agentList.add("Mozilla/5.0 (Windows NT 6.0; rv:2.0) Gecko/20100101 Firefox/4.0 Opera 12.14");
        agentList.add("Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0) Opera 12.14");
        agentList.add("Opera/12.80 (Windows NT 5.1; U; en) Presto/2.10.289 Version/12.02");
        agentList.add("Opera/9.80 (Windows NT 6.1; U; es-ES) Presto/2.9.181 Version/12.00");
        agentList.add("Opera/9.80 (Windows NT 5.1; U; zh-sg) Presto/2.9.181 Version/12.00");
        agentList.add("Opera/12.0(Windows NT 5.2;U;en)Presto/22.9.168 Version/12.00");
        agentList.add("Opera/12.0(Windows NT 5.1;U;en)Presto/22.9.168 Version/12.00");
        agentList.add("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1");
        agentList.add("Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0");
        agentList.add("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10; rv:33.0) Gecko/20100101 Firefox/33.0");
        agentList.add("Mozilla/5.0 (X11; Linux i586; rv:31.0) Gecko/20100101 Firefox/31.0");
        agentList.add("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20130401 Firefox/31.0");
        agentList.add("Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0");
        agentList.add("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.13 Safari/537.36");
        agentList.add("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3756.400 QQBrowser/10.5.4043.400");
    }

    private static String getRandomUA(){
        return agentList.get(RandomUtils.nextInt(0,agentList.size() - 1));
    }

}
